package org.example.main.utils;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
@Order(1)
public class LogAspect {
    private static final Logger logger = Logger.getLogger(LogAspect.class);

    // 定义切点，匹配service包下的所有类的所有方法
    @Pointcut("execution(public * org.example.main.service.*.*(..))")
    public void serviceLog() {}

    // 定义切点，匹配service.impl包下的所有类的所有方法
    @Pointcut("execution(public * org.example.main.service.impl.*.*(..))")
    public void serviceImplLog() {}

    @Before("serviceImplLog()")
    public void doBefore(JoinPoint joinPoint){
        logger.info("Method Start: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.debug("Arguments: " + Arrays.toString(joinPoint.getArgs()));
    }

    @After("serviceImplLog()")
    public void doAfter(JoinPoint joinPoint){
        logger.info("Method End: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    }

    @AfterReturning(returning ="result",pointcut = "serviceImplLog()")
    public void doAfterReturning(Object result){
        logger.debug("Method Return: " + result);
    }

    @AfterThrowing(pointcut = "serviceImplLog()", throwing = "exception")
    public void doAfterThrowing(JoinPoint joinPoint, Exception exception){
        logger.error("Exception in method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), exception);
    }
}
